import { Component, OnInit } from '@angular/core';

import "../../../assets/js/particles.min.js";
// import "../../../assets/js/app.js";
import "../../../assets/js/jquery-1.10.2.min.js";
import "../../../assets/js/jquery.qrcode.min.js";




import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { Router } from '@angular/router';

declare var layui: any;
declare var layer: any;
declare var $: any;
declare var particlesJS: any;
declare var jQuery: any;
const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };

import {
  FormBuilder,
  FormGroup,
  Validators
} from '@angular/forms';

import { PagesService } from '../../services/pages.service';
import { NzModalRef, NzFormatEmitEvent, NzModalService, NzMessageService } from 'ng-zorro-antd';
import { IfStmt } from '@angular/compiler';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  constructor(public router: Router, private http: HttpClient, public interfaceService: PagesService, private fb: FormBuilder, private nzMessageService: NzMessageService) { }
  // yzmurl="http://192.168.5.4:8080/";

  compareFn = (o1: any, o2: any) => o1 && o2 ? o1.value === o2.value : o1 === o2;
  gkyz_zzcj_log(value: { label: string, value: string }): void {
    //this.gkyz_zzcj=value;
  }
  username = "";
  password = "";
  ValidateCode = "";
  ljmc_List;
  ljmc;
  nodes;
  gkxzIndex = 1;
  gkxzSize = 10;
  gkxztotal = 1;
  url = "/erp/user/login";
  canshu = '';
  login() {
    var patrn = /\S/;// 不能为空
    if (!this.loginCode && !patrn.test(this.ValidateCode)) {
      this.nzMessageService.info('请输入验证码！');
    } else {
      if (!patrn.test(this.username) || !patrn.test(this.password)) {
        this.nzMessageService.info("账号或密码不能为空！");
      } else {
        var data = { prsnlCode: this.username, userPwd: this.password, domainId: this.ljmc, validateCode: this.ValidateCode };
        this.interfaceService.postPage(this.url, data).subscribe((data: any) => {
          if (this.interfaceService.codeValidation(data)) {
          if (data.code == 200) {
            const datas = data.object;
            localStorage.setItem('num', '');
            localStorage.setItem("ownerId", datas.ownerId);
            localStorage.setItem("userId", datas.userId);
            localStorage.setItem("userIdByWebSocket", datas.userIdByWebSocket);
            localStorage.setItem("isType", datas.isType);
            localStorage.setItem("name", datas.prsnl.fullName);
            localStorage.setItem("domainId", datas.domain.domainId);
            localStorage.setItem("unitId", datas.unit.unitId);
            localStorage.setItem("unitCode", datas.unit.unitCode);
            localStorage.setItem("unitName", datas.unit.unitName);
            localStorage.setItem("priviAll", JSON.stringify(datas.privilegeSet));
            localStorage.setItem("lockScreenTime", datas.lockScreenTime);//锁屏时间
            localStorage.setItem("htmlPollingTime", datas.htmlPollingTime);//轮询时间
            // this.router.navigate(['/home']);
            localStorage.setItem('login', 'login');
            window.location.replace("/");
          } else {
            this.nzMessageService.info(data["message"]);
            // this.addClass(document.querySelector(".login"), "active");
            //   setTimeout(()=>{
            //     this.addClass(document.querySelector(".sk-rotating-plane"), "active");
            //     $('.login').css("display","none");
            //   },800)
            //   setTimeout(()=>{
            //     this.removeClass(document.querySelector(".login"), "active");
            //     this.removeClass(document.querySelector(".sk-rotating-plane"), "active");
            //     $('.login').css("display","block");
            // },3000);
            // this.username="";
            // this.password="";
          }
        }
        });
      }
    }
  }


  keyDown(e) {
    if (e.keyCode == 13) {//按下哪个键
      if (this.ValidateCode) {
        this.login();
      } else {
        this.nzMessageService.info("请输入验证码！");
      }
    }
  }

  passwordEnter() {
    if (!this.loginCode) {
      $('#ValidateCode').focus();
    } else {
      this.login();
    }
  }


  yzmimg = "/erp/user/validate/code";
  showYzm() {
    this.yzmimg = "/erp/user/validate/code?1=" + Math.random();
  }

  onusername() {
    if (this.username.trim()) {
      var data = { prsnlCode: this.username };
      this.interfaceService.postPage("/erp/user/multipleUserDomains", data).subscribe((data: any) => {
        if (this.interfaceService.codeValidation(data)) {
        this.nodes = data;
        if (this.nodes.code == 200) {
          this.ljmc_List = data.object;
          this.ljmc = data.object[0].optionValue;
          this.loginDomain = false
          this.loginSub = false
        } else {
          this.loginDomain = true
          this.loginSub = true
          this.nzMessageService.info(this.nodes["message"]);
        }
      }
      });
    } else {
      this.loginDomain = true
      this.loginSub = true
    }
  }



  loginSub = true //提交按钮是否禁用
  loginDomain = true  //领域是否显示
  loginCode = true  //验证码是否显示
  loginHeight = '400px' //登录区域初始高度
  loginMsg=localStorage.getItem('loginMsg');
  ngOnInit() {
    this.lizi();
    this.isCode();
    this.onusername();
    localStorage.setItem('login', 'out');
    this.moreLoginImg();
    if(this.loginMsg){
      this.nzMessageService.info(this.loginMsg);
      localStorage.setItem('loginMsg', '');
    }
  }

  /**
   * 验证码是否启用
   */
  isCode() {
    this.interfaceService.postPage("/erp/user/validate/isCode", {}).subscribe((data: any) => {
      if (this.interfaceService.codeValidation(data)) {
      if (data.object === 'F' || data.object === 'f') {
        this.loginCode = true;
      } else {
        this.loginCode = false;
      }
    }
    });
  }


  /**
   * 登录界面尺寸变化设置
   */
  loginSize() {
    if (this.moreLoginState) {
      this.loginHeight = '500px';
    } else if (this.loginDomain && this.loginCode) {
      this.loginHeight = '500px';
    } else if (this.loginDomain || this.loginCode) {
      this.loginHeight = '440px';
    } else {
      this.loginHeight = '400px';
    }
  }

  /**
   * 第三方登录方式，图标加载
   */
  moreLoginList = []
  moreLoginState = false
  moreLoginImg() {
    this.interfaceService.postPage("/erp/scanCode/scanCodeList", {}).subscribe((data: any) => {
      if (this.interfaceService.codeValidation(data)) {
      if (data.code == 200) {
        this.moreLoginList = data.object;
      }
    }
    });
  }

  /**
   * 第三方登录
   */
  moreLoginTitle
  moreLoginImage
  moreLogin(e) {
    this.moreLoginState = true;
    this.loginSize();
    this.moreLoginTitle = e.thirdSysName + '扫码登录'
    this.interfaceService.postPage("/erp/scanCode/getThirdSys", e).subscribe((data: any) => {
      if (this.interfaceService.codeValidation(data)) {
      if (data.code == 200) {
        this.moreLoginImage = data.object;
        jQuery(function () {
          jQuery('#qrcode').qrcode({
            render: "canvas", //也可以替换为table
            width: 260,
            height: 260,
            text: data.object.QrUrl
          });
        })
        this.socketUrl = 'ws://erp.boyu.site/webSocketScanCode/' + data.object.Code;
        this.createWebSocket()
      }
    }
    });

  }

  /**
   * 返回账号密码登录
   */
  userLogin() {
    this.moreLoginState = false;
    this.webSocket.close();
    this.loginSize();
  }

  private socketUrl;                              // 默认请求的url
  private webSocket: WebSocket;                   // websocket对象

  /**
   * 创建连接
   */
  createWebSocket() {
    // 如果没有建立过连接，才建立连接并且添加时间监听
    this.webSocket = new WebSocket(this.socketUrl);
    console.log(this.socketUrl);
    // 建立连接成功
    this.webSocket.onopen = (e) => this.onOpen(e);
    // 接收到消息
    this.webSocket.onmessage = (e) => this.onMessage(e);
    // 连接关闭
    this.webSocket.onclose = (e) => this.onClose(e);
    // 异常
    this.webSocket.onerror = (e) => this.onError(e);
  }

  /**
  * 连接打开
  * @param e 打开事件
  */
  onOpen(e) {
    console.log('第三方登录websocket 已连接', e);
  }

  /**
   * 接受到消息
   */
  onMessage(e) {
    var data = JSON.parse(e['data'])
    if (this.interfaceService.codeValidation(data)) {
    if (data.code === '200') {
      this.webSocket.close()
      window.location = data.message;
    } else {
      this.nzMessageService.info(data.message);
    }
  }
  }


  /**
   * 连接关闭
   */
  private onClose(e) {
    console.log('第三方登录websocket 连接关闭', e);
  }

  /**
   * 连接异常
   */
  private onError(e) {
    console.log('第三方登录websocket 连接异常', e);
  }





  hasClass(elem, cls) {
    cls = cls || '';
    if (cls.replace(/\s/g, '').length == 0) return false; //当cls没有参数时，返回false
    return new RegExp(' ' + cls + ' ').test(' ' + elem.className + ' ');
  }

  addClass(ele, cls) {
    if (!this.hasClass(ele, cls)) {
      ele.className = ele.className == '' ? cls : ele.className + ' ' + cls;
    }
  }

  removeClass(ele, cls) {
    if (this.hasClass(ele, cls)) {
      var newClass = ' ' + ele.className.replace(/[\t\r\n]/g, '') + ' ';
      while (newClass.indexOf(' ' + cls + ' ') >= 0) {
        newClass = newClass.replace(' ' + cls + ' ', ' ');
      }
      ele.className = newClass.replace(/^\s+|\s+$/g, '');
    }
  }


  lizi() {
    particlesJS('particles-js',
      {
        "particles": {
          "number": {
            "value": 40,
            "density": {
              "enable": true,
              "value_area": 800
            }
          },
          "color": {
            "value": "#ffffff"
          },
          "shape": {
            "type": "circle",
            "stroke": {
              "width": 0,
              "color": "#000000"
            },
            "polygon": {
              "nb_sides": 5
            },
            "image": {
              "src": "img/github.svg",
              "width": 100,
              "height": 100
            }
          },
          "opacity": {
            "value": 0.7,
            "random": false,
            "anim": {
              "enable": false,
              "speed": 1,
              "opacity_min": 0.1,
              "sync": false
            }
          },
          "size": {
            "value": 3,
            "random": true,
            "anim": {
              "enable": false,
              "speed": 40,
              "size_min": 0.1,
              "sync": false
            }
          },
          "line_linked": {
            "enable": true,
            "distance": 150,
            "color": "#ffffff",
            "opacity": 0.6,
            "width": 1
          },
          "move": {
            "enable": true,
            "speed": 6,
            "direction": "none",
            "random": false,
            "straight": false,
            "out_mode": "out",
            "bounce": false,
            "attract": {
              "enable": false,
              "rotateX": 600,
              "rotateY": 1200
            }
          }
        },
        "interactivity": {
          "detect_on": "canvas",
          "events": {
            "onhover": {
              "enable": true,
              "mode": "grab"
            },
            "onclick": {
              "enable": true,
              "mode": "push"
            },
            "resize": true
          },
          "modes": {
            "grab": {
              "distance": 200,
              "line_linked": {
                "opacity": 1
              }
            },
            "bubble": {
              "distance": 400,
              "size": 40,
              "duration": 2,
              "opacity": 8,
              "speed": 3
            },
            "repulse": {
              "distance": 200,
              "duration": 0.4
            },
            "push": {
              "particles_nb": 4
            },
            "remove": {
              "particles_nb": 2
            }
          }
        },
        "retina_detect": false
      }

    );
  }







}
